<!DOCTYPE html>
<html>
  <head>
    <style>
      /* 保持原有样式不变 */
      .container {
        position: relative;
        border: 1px solid #ccc;
        margin: 20px;
      }
      #frameWrapper {
        width: 100%;
        /* height: 600px; */
      }
      iframe {
        width: 100%;
        /* height: 100%; */
        border: none;
      }
      .highlight-box {
        position: absolute;
        border: 2px solid rgba(0, 123, 255, 0.7);
        background-color: rgba(0, 123, 255, 0.2);
        z-index: 1000;
        pointer-events: none;
      }
      .controls {
        position: sticky;
        top: 0;
        z-index: 99999;
        margin: 10px;
        padding: 10px;
        background-color: #f5f5f5;
        border: 1px solid #ddd;
        border-radius: 4px;
      }
      .mode-btn {
        padding: 5px 10px;
        margin-right: 10px;
        cursor: pointer;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
      }
      #selectionInfo {
        margin-top: 10px;
        min-height: 20px;
        color: #666;
      }
    </style>
  </head>
  <body>
    <div class="controls">
      <button id="modeToggle" class="mode-btn">多选模式</button>
      <div id="selectionInfo"></div>
    </div>
    <div class="container">
      <div id="frameWrapper">
        <iframe id="targetFrame" src="./Vue.js.html"></iframe>
      </div>
    </div>

    <script>
      // 初始化变量
      let isMultiSelect = true;
      let selectedElements = [];
      let highlightElement = null;
      const iframe = document.getElementById("targetFrame");
      let isLocked = false; // 是否锁定
      let lastClickTime = 0; // 上次点击时间

      // 模式切换
      function toggleMode() {
        isMultiSelect = !isMultiSelect;
        document.getElementById("modeToggle").textContent = isMultiSelect ? "多选模式" : "单选模式";
        clearSelection();
      }

      // 初始化事件绑定
      function initSelection() {
        const iframeDoc = iframe.contentDocument;

        // 清理旧事件监听
        iframeDoc.removeEventListener("click", handleClick);
        iframeDoc.removeEventListener("mousemove", handleMouseMove);

        // 绑定新事件（使用捕获阶段）
        iframeDoc.addEventListener("click", handleClick, true);
        iframeDoc.addEventListener("mousemove", handleMouseMove, true);
      }

      // 鼠标移动处理（优化坐标计算）
      function handleMouseMove(e) {
        if (!isLocked) {
          const element = e.target;
          showHighlight(element);
        }
      }

      // 点击处理（增强阻止行为）
      function handleClick(e) {
        // 关键修复：彻底阻止默认行为和冒泡
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();

        const currentTime = Date.now();
        const element = e.target;

        if (currentTime - lastClickTime < 300) {
          // 双击
          isLocked = !isLocked;
          if (isLocked) {
            // 锁定高亮
            showHighlight(element);
          } else {
            // 解锁高亮
            removeHighlight();
          }
          lastClickTime = 0;
        } else {
          lastClickTime = currentTime;
          updateSelection(element);
        }
      }

      // 更新选择逻辑
      function updateSelection(element) {
        if (isMultiSelect) {
          // 多选模式，只保留最后一次选择
          selectedElements = [element];
        } else {
          // 单选模式
          selectedElements = [element];
        }
        updateSelectionInfo();
      }

      // 高亮显示优化（支持滚动位置）
      function showHighlight(element) {
        removeHighlight();

        const rect = element.getBoundingClientRect();
        const iframeRect = iframe.getBoundingClientRect();
        const scrollX = window.pageXOffset;
        const scrollY = window.pageYOffset;

        highlightElement = document.createElement("div");
        highlightElement.className = "highlight-box";
        highlightElement.style.left = `${rect.left + iframeRect.left + scrollX}px`;
        highlightElement.style.top = `${rect.top + iframeRect.top + scrollY}px`;
        highlightElement.style.width = `${rect.width}px`;
        highlightElement.style.height = `${rect.height}px`;

        document.body.appendChild(highlightElement);
      }

      // 移除高亮
      function removeHighlight() {
        if (highlightElement) {
          highlightElement.remove();
          highlightElement = null;
        }
      }

      // 清空选择
      function clearSelection() {
        selectedElements = [];
        updateSelectionInfo();
      }

      // 更新选择信息
      function updateSelectionInfo() {
        // 已经阻止则不能单击
        if (isLocked) {
          return;
        }
        const infoDiv = document.getElementById("selectionInfo");
        infoDiv.innerHTML = selectedElements
          .map((el) => {
            const selector = generateSelector(el);
            return `✅ 已选择元素：${selector}<br>`;
          })
          .join("");

        // 生成最终选择器
        const finalSelector = isMultiSelect ? selectedElements.map((el) => generateSelector(el)).join(", ") : generateSelector(selectedElements[0]);

        console.log("可用选择器:", finalSelector);
        console.log("对应DOM元素:", isMultiSelect ? document.querySelectorAll(finalSelector) : document.querySelector(finalSelector));
      }

      // 生成CSS选择器
      function generateSelector(element) {
        const path = [];
        while (element && element.nodeType === Node.ELEMENT_NODE) {
          let selector = element.tagName.toLowerCase();

          // 优先使用id
          if (element.id) {
            selector += `#${element.id}`;
            path.unshift(selector);
            break; // 有id时停止
          }

          // 添加class（如果有）
          if (element.classList.length > 0) {
            const classes = Array.from(element.classList).join(" ");
            selector += `.${classes}`;
          }

          // 添加属性（如name、data-*等）
          if (element.hasAttribute("name")) {
            selector += `[name="${element.getAttribute("name")}"]`;
          }
          // 单选使用nth-child更准确
          if (!isMultiSelect) {
            // 使用nth-child（比nth-of-type更可靠）
            let sibling = element;
            let nth = 1;
            while (sibling.previousElementSibling) {
              sibling = sibling.previousElementSibling;
              nth++;
            }
            if (nth > 1) {
              selector += `:nth-child(${nth})`;
            }
          }

          path.unshift(selector);
          element = element.parentElement;
        }
        return path.join(" ");
      }

      // 初始化流程
      iframe.addEventListener("load", () => {
        initSelection();
        iframe.height = iframe.contentWindow.document.body.scrollHeight + "px !important";
        // 注入阻止默认行为的全局样式
        const style = iframe.contentDocument.createElement("style");
        style.textContent = `
                * {
                    cursor: pointer !important;
                    pointer-events: auto !important;
                }
                a, [onclick] {
                    pointer-events: none !important;
                }
            `;
        iframe.contentDocument.head.appendChild(style);
      });

      // 初始化模式切换
      document.getElementById("modeToggle").addEventListener("click", toggleMode);
    </script>
  </body>
</html>
